package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.common.RedisConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Member;
import com.itheima.health.service.MemberService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 登录控制器
 */
@RestController
@RequestMapping("/mobile/login")
@Slf4j
@Api(tags = "手机端登录接口")
public class MobileLoginController {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MemberService memberService;

    @PostMapping("/smsLogin")
    public Result smsLogin(HttpServletRequest request, @RequestBody Map<String, String> data) {
//获取手机号验证码
        String telephone = data.get("telephone");
        String validateCode = data.get("validateCode");
        log.info("[手机端登录]手机号:{},验证码:{}", telephone, validateCode);
        if (Objects.equals(telephone, "") || Objects.equals(validateCode, "")) {
            return new Result(false, MessageConst.TELEPHONE_VALIDATECODE_NOTNULL);
        }
//从redis中检查验证码
        String redisVCode = (String) redisTemplate.opsForValue().get(telephone);
        if (!validateCode.equals(redisVCode)) {//判断验证是否失败
            return new Result(false, MessageConst.VALIDATECODE_ERROR);
        }
//验证成功删除redis验证码
        Boolean delete = redisTemplate.delete(telephone);

        //获取并封装会员信息,如果会员不存在,登录失败
        Member member = memberService.selectByPhoneNumber(telephone);
        if (member == null) {
//            member = new Member();
//            member.setPhoneNumber(telephone);
//            member.setRegTime(new Date());
//            memberService.register(member);
            return new Result(false,MessageConst.LOGIN_FAIL);
        }
        request.getSession().setAttribute("member", member);
        return new Result(true, MessageConst.LOGIN_SUCCESS);
    }

}
